package com.jay.io.intf;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;

public class ExternalizableIntf implements Externalizable {
	private String message;

	public String getFoo() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	private Object writeReplace() throws ObjectStreamException {
		System.out.println("writeReplace invoked");
		return this;
	}

	private Object readResolve() throws ObjectStreamException {
		System.out.println("readResolve invoked");
		return this;
	}

	public Object serialize() throws IOException, ClassNotFoundException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(this);
		ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(bais);
		return ois.readObject();
	}

	@Override
	public void readExternal(ObjectInput arg0) throws IOException,
			ClassNotFoundException {
		System.out.println("readExternal invoked");
		Object obj = arg0.readObject();
	}

	@Override
	public void writeExternal(ObjectOutput arg0) throws IOException {
		System.out.println("writeExternal invoked");
		arg0.writeObject("Hello world");
	}

	public static void main(String[] args) throws IOException,
			ClassNotFoundException {
		ExternalizableIntf fooimpl = new ExternalizableIntf();
		fooimpl.serialize();
	}
}
